package com.innovation.chengzhangriji.service;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;

import com.innovation.chengzhangriji.Config;
import com.innovation.chengzhangriji.ConfigurationManager;
import com.innovation.chengzhangriji.http.BaseRequest;
import com.innovation.library.http.InnovationClient;
import com.jiuan.oa.android.library.util.AESUtil;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import org.apache.http.Header;
import java.io.FileOutputStream;

public class SyncConfigService extends Service {

    static final String CONFIG_URL = BaseRequest.SHARE_PATH + "appconfigs/"
            + Config.VERSION +"/android/config.json";

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        downloadConfiguration();
        return super.onStartCommand(intent, flags, startId);
    }

    // 下载配置信息
    private void downloadConfiguration() {
        InnovationClient client = InnovationClient.getInstance();
        client.setSSLSocketFactory();
        client.get(getApplicationContext(), CONFIG_URL, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                try {
                    String config = AESUtil.decrypt(Config.AES_PASSWORD, new String(responseBody));
                    FileOutputStream output = new FileOutputStream(Config.getAppConfig(getApplicationContext()), false);
                    output.write(config.getBytes("UTF-8"));
                    output.close();
                    // 当前环境可能不生效，下次运行生效
                    ConfigurationManager.getInstance().loadConfig(getApplicationContext());
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                // Log.e("SyncConfigServiceTAG", new String(responseBody));
            }
        });
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}
